#!/bin/bash

# 设置文件备份函数
mk_bak() {
    local file_path="${@: -1}"
    if [ -e "${file_path}" ]
    then
        cp -av "${file_path}" "${file_path}.$(date +%F_%s)"
    else
        echo "not exist file ${file_path}"
    fi
}
#################################
##  /etc/ssh/sshd_config       ##
#################################
# sshd_cfg_list=(
#     'HostbasedAuthentication no'
#     'IgnoreRhosts yes'
#     'X11Forwarding no'
#     'LogLevel INFO'
#     'Protocol 2'
#     'Banner /etc/issue.net'
#     'LoginGraceTime 60'
#     'MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com'
# )

# cp -av /etc/ssh/sshd_config /etc/ssh/sshd_config.$(date +%F_%s) &&
# for i in "${sshd_cfg_list[@]}"
# do
#     j=$(echo $i |awk '{print $1}')
#     if grep -P "^\s*$j" /etc/ssh/sshd_config 
#     then
#         sed -i -r "/$j/c$i" /etc/ssh/sshd_config 
#     else
#         sed -i -r "\$a$i" /etc/ssh/sshd_config
#     fi
# done 
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
ssh_path='/etc/ssh/sshd_config'
typeset -A sshd_cfg_kv=(
    ['HostbasedAuthentication']='no'
    ['IgnoreRhosts']='yes'
    ['X11Forwarding']='no'
    ['LogLevel']='INFO'
    ['Protocol']='2'
    ['Banner']='/etc/issue.net'
    ['LoginGraceTime']='60'
    ['MACs']='hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com'
)

cp -av "${ssh_path}" "${ssh_path}.$(date +%F_%s)" &&
for key in "${!sshd_cfg_kv[@]}"
do
    value=${sshd_cfg_kv[$key]}
    if grep -iP "^\s*${key}" ${ssh_path}
    then
        # 注意：此处Ic表示忽略大小写匹配后替换原配置行
        sed -i -r "/^[ \t]*${key}/Ic${key} ${value} $(date +'#lhc_modify_setting@%F')" ${ssh_path}
    else
        sed -i -r "\$a${key} ${value} $(date +'#lhc_modify_setting@%F')" ${ssh_path}
    fi
done

mk_bak "/etc/issue.net" &&
echo "Tlinux 2.4" > "/etc/issue.net"
sshd -t &&
systemctl restart sshd


#################################
##       文件权限设置           ##
#################################
chown root:root /etc/cron.weekly
chmod og-rwx /etc/cron.weekly
chown root:root /etc/cron.d
chmod og-rwx /etc/cron.d
chown root:root /etc/cron.monthly
chmod og-rwx /etc/cron.monthly
chown root:root /etc/cron.daily
chmod og-rwx /etc/cron.daily
chown root:root /etc/cron.hourly
chmod og-rwx /etc/cron.hourly
chown root:root /etc/crontab
# 去掉r权限后user_00无法执行定时任务
# chmod og-rwx /etc/crontab


#################################
##       禁用风险服务           ##
#################################
systemctl disable avahi-daemon


#################################
##       调整系统设置           ##
#################################
# 备份
mount -l >> /var/log/mount.$(date +%s)
sysctl -a >> /var/log/sysctl.bak.$(date +%s)

# /dev/shm
mount -o remount,noexec,nosuid,nodev /dev/shm
fstab_path='/etc/fstab'
cp -av "${fstab_path}" "${fstab_path}.$(date +%F_%s)"
grep -P "[^#]*.*\s/dev/shm\s" "${fstab_path}" && 
sed -i -r "s|^[^#]*.*[ \t]/dev/shm[/ \t].*\$|tmpfs   /dev/shm  tmpfs   defaults,noexec,nosuid,nodev   0   0|" "${fstab_path}" || 
sed -i -r "\$atmpfs   /dev/shm  tmpfs   defaults,noexec,nosuid,nodev   0   0" "${fstab_path}"

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
sysctl_path='/etc/sysctl.conf'
typeset -A sysctl_cfg_kv=(
    ['net.ipv6.conf.all.accept_redirects']='0'
    ['net.ipv6.conf.default.accept_redirects']='0'
    ['net.ipv6.conf.all.accept_ra']='0'
    ['net.ipv6.conf.default.accept_ra']='0'
    ['net.ipv4.tcp_syncookies']='1'
    ['net.ipv4.conf.all.rp_filter']='1'
    ['net.ipv4.conf.default.rp_filter']='1'
    ['net.ipv4.conf.all.log_martians']='1'
    ['net.ipv4.conf.default.log_martians']='1'
    ['net.ipv4.conf.all.secure_redirects']='0'
    ['net.ipv4.conf.default.secure_redirects']='0'
    ['net.ipv4.conf.all.accept_redirects']='0'
    ['net.ipv4.conf.default.accept_redirects']='0'
    ['net.ipv4.conf.all.accept_source_route']='0'
    ['net.ipv4.conf.default.accept_source_route']='0'
    ['net.ipv4.conf.all.send_redirects']='0'
    ['net.ipv4.conf.default.send_redirects']='0'
    ['net.ipv4.ip_forward']='0'
)

mk_bak ${sysctl_path} &&
for key in "${!sysctl_cfg_kv[@]}"
do
    value=${sysctl_cfg_kv[$key]}
    if grep -iP "^\s*${key}" ${sysctl_path}
    then
        # 注意：此处Ic表示忽略大小写匹配后替换原配置行
        sed -i -r "/^[ \t]*${key} *=/Ic${key} = ${value}" ${sysctl_path}
    else
        sed -i -r "\$a${key} = ${value}" ${sysctl_path}
    fi
    sysctl -w "${key}=${value}"
done

sysctl -w net.ipv6.route.flush=1
sysctl -w net.ipv4.route.flush=1


cron_root_path='/var/spool/cron/root'
echo '' >> "${cron_root_path}"
echo "0 5 * * * /usr/sbin/aide --check" >> "${cron_root_path}"
#################################
##      调整系统审计设置         ##
#################################
audit_path='/etc/audit/rules.d/audit.rules'
typeset -a audit_cfg_v=(
    '-w /var/run/utmp -p wa -k session'
    '-w /var/log/wtmp -p wa -k logins'
    '-w /var/log/btmp -p wa -k logins'
    '-w /var/log/lastlog -p wa -k logins'
    '-w /var/run/faillock/ -p wa -k logins'
    '-w /etc/selinux/ -p wa -k MAC-policy'
    '-w /usr/share/selinux/ -p wa -k MAC-policy'
    '-w /etc/group -p wa -k identity'
    '-w /etc/passwd -p wa -k identity'
    '-w /etc/gshadow -p wa -k identity'
    '-w /etc/shadow -p wa -k identity'
    '-w /etc/security/opasswd -p wa -k identity'
    '-w /var/log/sudo.log -p wa -k actions'
    '-w /etc/sudoers -p wa -k scope'
    '-w /etc/sudoers.d/ -p wa -k scope'
#    '-e 2'
# 这条最后手动操作吧，跑完脚本验证没问题再执行这条
)

cp -av "${audit_path}" "${audit_path}.$(date +%F_%s)" &&
# 确保audit别锁
if grep -P "^\s*-e\s+2" "${audit_path}"
then
    sed -i -r '/-e[ \t]*2/d' "${audit_path}"
fi
# 开始写入
for value in "${audit_cfg_v[@]}"
do
    if ! grep -e "${value}" "${audit_path}"
    then
        sed -i -r "\$a${value}" "${audit_path}"
    fi
done

auditctl -R /etc/audit/rules.d/audit.rules
# 这里如果无法写入，可能是之前就被锁了，需要重启

systemctl enable auditd
systemctl restart auditd
echo '' >> '/etc/profile'
echo 'export TMOUT=180' >> '/etc/profile'
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
cp -av /boot/grub2/grub.cfg /boot/grub2/grub.cfg.$(date +%F_%s)
sed -i -r "\$aGRUB_CMDLINE_LINUX=\"audit=1\"" /etc/default/grub
grub2-mkconfig -o /boot/grub2/grub.cfg

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
audit_cfg_path='/etc/audit/auditd.conf'
typeset -A audit_cfg_kv=(
    ['max_log_file_action']='keep_logs'
# 下边三行如果设置，会导致日志写满强制关机，影响业务
    # ['space_left_action']='email'
    # ['action_mail_acct']='root'
    # ['admin_space_left_action']='halt'
)

cp -av "${audit_cfg_path}" "${audit_cfg_path}.$(date +%F_%s)" &&
for key in "${!audit_cfg_kv[@]}"
do
    value=${audit_cfg_kv[$key]}
    if grep -iP "^\s*${key}" ${audit_cfg_path}
    then
        # 注意：此处Ic表示忽略大小写匹配后替换原配置行
        sed -i -r "/^[ \t]*${key}/Ic${key} = ${value}" ${audit_cfg_path}
    else
        sed -i -r "\$a${key} = ${value}" "${audit_cfg_path}"
    fi
done

#################################
##    特殊文件系统、协议禁用     ##
#################################
# 设置路径
cis_cfg_path="/etc/modprobe.d/CIS.conf"
# 备份旧配置文件，如果不存在旧算了
test -e "${cis_cfg_path}" && 
cp -av "${cis_cfg_path}" "${cis_cfg_path}.$(date +%F_%s)" || 
echo '' >> "${cis_cfg_path}"
# 需要修改的内容的列表
typeset -a cis_cfg_a=(
    'cramfs'
    'dccp'
    'freevxfs'
    'hfs'
    'hfsplus'
    'jffs2'
    'rds'
    'sctp'
    'squashfs'
    'tipc'
    'udf'
)
for value in "${cis_cfg_a[@]}"
do
    if grep -P "^\s*install\s+${value}\s+/bin/true" "${cis_cfg_path}"
    then
        sed -i -r "s|^[ \t]*install${value}[ \t]*/bin/true.*\$|install ${value} /bin/true|" "${cis_cfg_path}"
    else
        sed -i -r "\$ainstall ${value} /bin/true" "${cis_cfg_path}"
    fi
    rmmod "${value}"
done

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # 
